package cmms.session;

import javax.servlet.http.HttpServletRequest;

import fab.web.mvc.AbstractUserSession;
import fab.web.mvc.ISessionManager;
import fab.web.mvc.dao.DaoProvider;
import fab.web.mvc.dao.IDao;

public class SessionManager implements ISessionManager<UserSession> {
	// session超时间隔（单位分钟）
	private long timeout = 30 * 60 * 1000;

	// 转换配置的分钟到毫秒
	public void setTimeout(int minits) {
		this.timeout = timeout * 60 * 1000;
	}

	private long privilegeRefresh;

	private DaoProvider daoProvider;

	public void setDaoProvider(DaoProvider daoProvider) {
		this.daoProvider = daoProvider;
	}

	private PrivilegeManager privilegeManager;

	public void setPrivilegeManager(PrivilegeManager privilegeManager) {
		this.privilegeManager = privilegeManager;
	}

	public void init() throws Exception {
		if (privilegeManager != null) {
			IDao dao = daoProvider.get(null);
			try {
				reloadPrivilege(dao);
			} finally {
				daoProvider.releaseAll();
			}
		}
	}

	/**
	 * 重新load权限缓存（外部可调用）
	 * 
	 * @param dao
	 * @throws Exception
	 */
	public void reloadPrivilege(IDao dao) throws Exception {
		if (privilegeManager != null) {
			// 不启用数据库角色权限判断
			// privilegeRefresh = privilegeManager.load(dao);
		}
	}

	public UserSession find(HttpServletRequest request) {
		UserSession session = (UserSession) request.getSession()
				.getAttribute(AbstractUserSession.USER_SESSION);

		return session;
	}



	public void release(UserSession session, HttpServletRequest request) {
		request.getSession().invalidate();

	}

	/**
	 * 
	 * @param request
	 * @param client
	 * @param args
	 *            [0]用户AddUserBo 对象 args[1] sessionId = (单点登录用)
	 * @return
	 * @throws Exception
	 */
	public UserSession createSession(HttpServletRequest request, Object... args) throws Exception {
		UserSession us = new UserSession();

		return us;
	}

	public PrivilegeManager getPrivilegeManager() {
		return privilegeManager;
	}

	@Override
	public void setPrivilege(HttpServletRequest request, UserSession session)
			throws Exception {
		if (privilegeManager != null && session != null) {
			// 根据角色设置用户权限
			privilegeManager.setUserPrivilege(session);
			// 设置权限刷新
			session.setPrivilegeRefresh(privilegeRefresh);
		}
		request.getSession().setAttribute(AbstractUserSession.USER_SESSION,
				session);

	}

	@Override
	public void fini() {
		// TODO Auto-generated method stub

	}


}